﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YourFileWatcher.Services
{

    /// <summary>
    /// 操作本地文件的逻辑
    /// </summary>
    public class LocalFileService
    {

        /// <summary>
        /// 打开一个“选择文件”对话框，选择多个文件后，获取文件的绝对路径组合，如果用户取消了选择，会返回NULL
        /// </summary>
        /// <param name="pFilter">筛选器字符串，该字符串确定显示的文件类型</param>
        /// <returns>文件绝对路径列表，可能是NULL</returns>
        public string[] DialogSelectFileListingGetPath(string pFilter = null)
        {
            string[] result = null;

            var openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            if (!String.IsNullOrWhiteSpace(pFilter))
            {
                openFileDialog.Filter = pFilter;
            }
            var r = openFileDialog.ShowDialog();
            if (r == DialogResult.OK || r == DialogResult.Yes)
            {
                result = openFileDialog.FileNames;
            }

            return result;
        }
        
        /// <summary>
        /// 打开一个“文件另存为”对话框，选择一个位置，返回指定的位置，可能返回空字符串（用户未选择正确的位置）
        /// </summary>
        /// <param name="pFileName">要保存的默认文件名</param>
        /// <param name="pSourceFile">默认文件名，可能是 String.Empty</param>
        public string DialogSaveFileFullPath(string pFileName)
        {
            string result = String.Empty;

            System.Windows.Forms.SaveFileDialog saveDialog = new System.Windows.Forms.SaveFileDialog();
            saveDialog.FileName = pFileName;
            saveDialog.DefaultExt = Path.GetExtension(pFileName);
            saveDialog.Filter = "文件格式|*" + saveDialog.DefaultExt;
            if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                result = saveDialog.FileName;
            }
            return result;
        }

        /// <summary>
        /// 打开一个“选择目录”对话框，选择一个目录后，获取目录的绝对路径，如果用户取消了选择，会返回NULL
        /// </summary>
        /// <returns>文件绝对路径列表，可能是 String.Empty</returns>
        public string DialogSelectDirectoryGetPath()
        {
            string result = String.Empty;

            FolderBrowserDialog fb = new FolderBrowserDialog();

            var r = fb.ShowDialog();
            if (r == DialogResult.OK || r == DialogResult.Yes)
            {
                result = fb.SelectedPath;
            }

            return result;
        }

        /// <summary>
        /// 获取给定的路径，用 “资源管理器” 打开并定位到指定位置
        /// </summary>
        /// <param name="path">要定位的路径</param>
        public void ExplorerPath(string path)
        {
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
            psi.Arguments = "/e,/select," + path;
            System.Diagnostics.Process.Start(psi);
        }
    }
}
